package cn.zust.itcost.service.impl;

import cn.zust.itcost.entity.graph.node.*;
import cn.zust.itcost.repository.ResumeRepository;
import cn.zust.itcost.service.ResumeService;
import cn.zust.itcost.utils.PdfUtils;
import cn.zust.itcost.utils.TextAnalyzer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Slf4j
@Service
public class ResumeServiceImpl implements ResumeService {

    @Autowired
    private ResumeRepository resumeRepository;
    
    @Autowired
    private TextAnalyzer textAnalyzer;

    @Override
    public Map<String, Object> parseAndSaveResume(MultipartFile file) throws IOException {
        log.info("开始解析简历文件: {}", file.getOriginalFilename());
        
        // 1. 提取PDF文本内容
        String content = PdfUtils.extractText(file);
        log.info("PDF文本内容长度: {} 字符", content.length());
        log.debug("PDF文本内容: {}", content);
        
        // 使用TextAnalyzer进行文本分析
        List<String> skills = textAnalyzer.extractSkills(content);
        Map<String, List<String>> educationInfo = textAnalyzer.extractEducationInfo(content);
        Map<String, List<String>> workExperience = textAnalyzer.extractWorkExperience(content);
        Map<String, Double> keywords = textAnalyzer.extractKeywords(content, 10);
        
        // 2. 创建简历节点
        ResumeNode resume = new ResumeNode();
        resume.setName(file.getOriginalFilename());
        resume.setSource(file.getOriginalFilename());
        resume.setUploadTime(LocalDateTime.now().format(DateTimeFormatter.ISO_DATE_TIME));
        resume.setContent(content);
        
        // 3. 解析教育经历
        List<EducationNode> educations = parseEducation(content);
        log.info("解析到教育经历数量: {}", educations.size());
        for (EducationNode education : educations) {
            log.info("教育经历详情: 学校={}, 专业={}, 学位={}, 开始时间={}, 结束时间={}", 
                education.getSchool(), education.getMajor(), education.getDegree(),
                education.getStartDate(), education.getEndDate());
        }
        resume.setEducations(educations);
        
        // 4. 解析工作经历
        List<ExperienceNode> experiences = parseExperience(content);
        log.info("解析到工作经历数量: {}", experiences.size());
        for (ExperienceNode experience : experiences) {
            log.info("工作经历详情: 公司={}, 职位={}, 开始时间={}, 结束时间={}, 描述={}, 成就={}", 
                experience.getCompany(), experience.getPosition(),
                experience.getStartDate(), experience.getEndDate(),
                experience.getDescription(), experience.getAchievements());
        }
        resume.setExperiences(experiences);
        
        // 5. 解析技能
        List<SkillNode> skillsNodes = new ArrayList<>();
        for (String skill : skills) {
            SkillNode skillNode = new SkillNode();
            skillNode.setName(skill);
            skillsNodes.add(skillNode);
        }
        resume.setSkills(skillsNodes);
        
        // 6. 保存到Neo4j
        ResumeNode savedResume = resumeRepository.save(resume);
        log.info("简历保存成功，ID: {}", savedResume.getId());
        
        // 7. 返回结果
        Map<String, Object> result = new HashMap<>();
        result.put("resumeId", savedResume.getId());
        result.put("educationCount", educations.size());
        result.put("experienceCount", experiences.size());
        result.put("skillCount", skillsNodes.size());
        result.put("keywords", keywords);
        
        return result;
    }

    private List<EducationNode> parseEducation(String content) {
        List<EducationNode> educations = new ArrayList<>();
        log.debug("开始解析教育经历，内容长度: {}", content.length());
        
        // 尝试多种教育经历匹配模式
        String[] educationPatterns = {
            "教育经历\\s*(.*?)(?=个人优势|工作经历|项目经历|$)",
            "教育背景\\s*(.*?)(?=个人优势|工作经历|项目经历|$)",
            "学历\\s*(.*?)(?=个人优势|工作经历|项目经历|$)"
        };
        
        for (String patternStr : educationPatterns) {
            Pattern pattern = Pattern.compile(patternStr, Pattern.DOTALL);
            Matcher matcher = pattern.matcher(content);
            
            if (matcher.find()) {
                String educationText = matcher.group(1);
                log.debug("找到教育经历文本: {}", educationText);
                
                // 尝试匹配学校、专业、学位等信息
                Pattern schoolPattern = Pattern.compile("([^，。]+(大学|学院|学校))");
                Pattern majorPattern = Pattern.compile("([^，。]+(专业|系))");
                Pattern degreePattern = Pattern.compile("(本科|硕士|博士|学士|研究生)");
                Pattern datePattern = Pattern.compile("(\\d{4})[\\-至](\\d{4})");
                
                String[] lines = educationText.split("\n");
                for (String line : lines) {
                    if (line.trim().isEmpty()) continue;
                    
                    EducationNode education = new EducationNode();
                    
                    Matcher schoolMatcher = schoolPattern.matcher(line);
                    if (schoolMatcher.find()) {
                        education.setSchool(schoolMatcher.group(1));
                        log.debug("找到学校: {}", education.getSchool());
                    }
                    
                    Matcher majorMatcher = majorPattern.matcher(line);
                    if (majorMatcher.find()) {
                        education.setMajor(majorMatcher.group(1));
                        log.debug("找到专业: {}", education.getMajor());
                    }
                    
                    Matcher degreeMatcher = degreePattern.matcher(line);
                    if (degreeMatcher.find()) {
                        education.setDegree(degreeMatcher.group(1));
                        log.debug("找到学位: {}", education.getDegree());
                    }
                    
                    Matcher dateMatcher = datePattern.matcher(line);
                    if (dateMatcher.find()) {
                        education.setStartDate(dateMatcher.group(1));
                        education.setEndDate(dateMatcher.group(2));
                        log.debug("找到日期: {} - {}", education.getStartDate(), education.getEndDate());
                    }
                    
                    education.setDescription(line);
                    educations.add(education);
                }
            }
        }
        
        return educations;
    }

    private List<ExperienceNode> parseExperience(String content) {
        List<ExperienceNode> experiences = new ArrayList<>();
        log.debug("开始解析工作经历，内容长度: {}", content.length());
        
        // 尝试多种工作经历匹配模式
        String[] experiencePatterns = {
            "工作经历\\s*(.*?)(?=项目经历|教育经历|$)",
            "工作经验\\s*(.*?)(?=项目经历|教育经历|$)",
            "实习经历\\s*(.*?)(?=项目经历|教育经历|$)"
        };
        
        for (String patternStr : experiencePatterns) {
            Pattern pattern = Pattern.compile(patternStr, Pattern.DOTALL);
            Matcher matcher = pattern.matcher(content);
            
            if (matcher.find()) {
                String experienceText = matcher.group(1);
                log.debug("找到工作经历文本: {}", experienceText);
                
                // 尝试匹配公司、职位、日期等信息
                Pattern companyPattern = Pattern.compile("([^，。]+(公司|集团|科技|网络|信息|软件))");
                Pattern positionPattern = Pattern.compile("([^，。]+(工程师|开发|经理|主管|总监|专员|产品经理))");
                Pattern datePattern = Pattern.compile("(\\d{4}\\.\\d{1,2})[\\-至](\\d{4}\\.\\d{1,2})");
                Pattern contentPattern = Pattern.compile("内容[：:](.*?)(?=业绩|成果|$)");
                Pattern achievementPattern = Pattern.compile("(业绩|成果)[：:](.*?)(?=\\n|$)");
                
                String[] lines = experienceText.split("\n");
                for (String line : lines) {
                    if (line.trim().isEmpty()) continue;
                    
                    ExperienceNode experience = new ExperienceNode();
                    
                    Matcher companyMatcher = companyPattern.matcher(line);
                    if (companyMatcher.find()) {
                        experience.setCompany(companyMatcher.group(1));
                        log.debug("找到公司: {}", experience.getCompany());
                    }
                    
                    Matcher positionMatcher = positionPattern.matcher(line);
                    if (positionMatcher.find()) {
                        experience.setPosition(positionMatcher.group(1));
                        log.debug("找到职位: {}", experience.getPosition());
                    }
                    
                    Matcher dateMatcher = datePattern.matcher(line);
                    if (dateMatcher.find()) {
                        experience.setStartDate(dateMatcher.group(1));
                        experience.setEndDate(dateMatcher.group(2));
                        log.debug("找到日期: {} - {}", experience.getStartDate(), experience.getEndDate());
                    }
                    
                    Matcher contentMatcher = contentPattern.matcher(line);
                    if (contentMatcher.find()) {
                        experience.setDescription(contentMatcher.group(1));
                        log.debug("找到描述: {}", experience.getDescription());
                    }
                    
                    Matcher achievementMatcher = achievementPattern.matcher(line);
                    if (achievementMatcher.find()) {
                        experience.setAchievements(achievementMatcher.group(2));
                        log.debug("找到成就: {}", experience.getAchievements());
                    }
                    
                    experiences.add(experience);
                }
            }
        }
        
        return experiences;
    }

    @Override
    public ResumeNode getResumeById(Long resumeId) {
        return resumeRepository.findById(resumeId)
                .orElseThrow(() -> new RuntimeException("简历不存在"));
    }

    @Override
    public List<ResumeNode> searchResumes(String keyword) {
        return resumeRepository.findByContentContaining(keyword);
    }

    @Override
    public List<ResumeNode> getAllResumes() {
        return resumeRepository.findAll();
    }

    @Override
    public Map<String, Object> saveResumeForm(Map<String, String> formData) {
        log.info("开始保存简历表单数据: {}", formData);
        
        // 1. 创建简历节点
        ResumeNode resume = new ResumeNode();
        resume.setName(formData.get("name"));
        resume.setSource("表单提交");
        resume.setUploadTime(LocalDateTime.now().format(DateTimeFormatter.ISO_DATE_TIME));
        
        // 2. 解析教育经历
        List<EducationNode> educations = new ArrayList<>();
        if (formData.containsKey("educationHistory")) {
            EducationNode education = new EducationNode();
            education.setSchool(formData.get("education"));
            education.setDescription(formData.get("educationHistory"));
            educations.add(education);
        }
        resume.setEducations(educations);
        
        // 3. 解析工作经历
        List<ExperienceNode> experiences = new ArrayList<>();
        if (formData.containsKey("workExperience3")) {
            ExperienceNode experience = new ExperienceNode();
            experience.setDescription(formData.get("workExperience3"));
            experiences.add(experience);
        }
        if (formData.containsKey("workExperience4")) {
            ExperienceNode experience = new ExperienceNode();
            experience.setDescription(formData.get("workExperience4"));
            experiences.add(experience);
        }
        resume.setExperiences(experiences);
        
        // 4. 解析技能
        List<SkillNode> skills = new ArrayList<>();
        if (formData.containsKey("workExperience1")) {
            String[] skillNames = formData.get("workExperience1").split("[；;]");
            for (String skillName : skillNames) {
                if (!skillName.trim().isEmpty()) {
                    SkillNode skill = new SkillNode();
                    skill.setName(skillName.trim());
                    skills.add(skill);
                }
            }
        }
        resume.setSkills(skills);
        
        // 5. 保存到Neo4j
        ResumeNode savedResume = resumeRepository.save(resume);
        log.info("简历表单保存成功，ID: {}", savedResume.getId());
        
        // 6. 返回结果
        Map<String, Object> result = new HashMap<>();
        result.put("resumeId", savedResume.getId());
        result.put("educationCount", educations.size());
        result.put("experienceCount", experiences.size());
        result.put("skillCount", skills.size());
        
        return result;
    }
} 